package com.neuedu.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

/**
 * Servlet implementation class UploadServ
 */
@WebServlet("/UploadServ")
public class UploadServ extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public UploadServ() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		DiskFileItemFactory diskfile =new DiskFileItemFactory();//创建文件上传解析器
		ServletFileUpload servletfileupload= new ServletFileUpload(diskfile);//判断前端form表单是否为enctype="multipart/form-data"属性
		servletfileupload.setHeaderEncoding("utf-8");
		servletfileupload.setFileSizeMax(10*1024*1024);
		try {
			List<FileItem> parseRequest =servletfileupload.parseRequest(request);
			for (FileItem fileItem : parseRequest) {
				if(!(fileItem.isFormField()))
				{
					System.out.println(fileItem.getName());
					InputStream inputstream =fileItem.getInputStream();
					File file =new File("D:/test/"+fileItem.getName());
					FileOutputStream fos = new FileOutputStream(file);
					int lean = 0;
					byte[] buffer=new byte[1024];
					while((lean=inputstream.read(buffer))!=-1)
					{
						fos.write(buffer, 0, lean);
					}
					fos.close();
					inputstream.close();
				}
			}
		} catch (FileUploadException e) {
			e.printStackTrace();
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}
